function numberToChinese(num: number): string {
  var result = "";
  var numStr = num.toString();
  // 判断是不是负数
  if (num < 0) {
    result += "负";
    numStr = numStr.slice(1);
  }
  // 处理整数部分
  if (numStr.includes(".")) {
    result += decimalToChinese(numStr);
  } else {
    result += intergerToChinese(numStr);
  }
  return result;
}

function decimalToChinese(decimal: string): string {
  const digits = ["零", "一", "二", "三", "四", "五", "六", "七", "八", "九"];
  var result = "";
  let integerPart = decimal.split(".")[0];
  let decimalPart = decimal.split(".")[1];
  result += intergerToChinese(integerPart);
  result += "点";
  for (let i = 0; i < decimalPart.length; i++) {
    result += digits[parseInt(decimalPart[i])];
  }
  return result;
}

function intergerToChinese(int: string): string {
  const units = ["", "万", "亿", "万亿"];
  // 循环几次
  const count =
    int.length % 4 === 0
      ? parseInt((int.length / 4).toString())
      : parseInt((int.length / 4).toString()) + 1;
  var result = "";
  if (count > units.length) {
    return "超出范围";
  }
  for (let i = 0; i < count; i++) {
    let end = int.length - i * 4;
    let start = end - 4 < 0 ? 0 : end - 4;
    let part = int.slice(start, end);
    var interger4 = interger4ToChinese(part);
    if (interger4) interger4 += units[i];
    result = interger4 + result;
  }
  return result;
}

function interger4ToChinese(int: string): string {
  // 定义数字和单位的映射
  const digits = ["零", "一", "二", "三", "四", "五", "六", "七", "八", "九"];
  const units = ["", "十", "百", "千"];
  var result = "";
  for (let i = int.length - 1; i >= 0; i--) {
    let digit = int[i];
    if (digit !== "0") {
      result = digits[parseInt(digit)] + units[int.length - i - 1] + result;
    } else {
      // 处理连续的零
      if (result[0] !== "零") {
        result = "零" + result;
      }
    }
  }
  return result.endsWith("零") ? result.slice(0, -1) : result;
}

export default numberToChinese;
